const router = require('koa-router')(); //注意：引入的方式
const db = require('../utils/database.js')
const io = require('../index')

router.prefix('/order')

router.get('/', ctx => {
	ctx.body = "order--index";
})

router.get('/allList', async ctx => {
	const data = await db.findAll('order', {})
	ctx.body = { success: true, code: 20000, message: "数据查询成功", data }
})

// socket
io.on('connection', socket => {
	socket.on('pay', res => {
		(async () => {
			const orderAll = await db.findAll('order', {}, { time: -1 })
			const orderUnpay = await db.findAll('order', { status: 0 }, { time: -1 })
			const serveTable = await db.findAll('table', { status: true, state: '1' })
			const freeTable = await db.findAll('table', { status: true, state: '0' })
			const totalTable = await db.findAll('table', {})
			io.emit('worktable', { orderAll, orderUnpay, serveTable, freeTable, totalTable })
		})()
	})
})

// 查询 分页 搜索 排序
router.get('/list', async ctx => {
	const { order, by, page = 0, pageSize = 20, query } = ctx.request.query // request可省略
	let sort = {},
		where = {}
	if (by) {
		sort[by] = order // by是条件 order是-1或1
	}
	if (query) { // 桌号
		where.tableNum = { $regex: new RegExp(query) }
	}
	//总条数
	const total = await db.total('order', where)
	const data = await db.find('order', { where, sort, skip: page * pageSize, limit: pageSize })
	ctx.body = { success: true, code: 20000, message: "数据查询成功", data, total }
})

// 新增
router.post('/save', async ctx => {
	const { tableNum, totalMoney, peopleNum, dishInfo, notes } = ctx.request.body;
	// status 0是未结账 1是已结账 默认是未结账 // dishInfo是数组，里边存放菜品的名称，数量，单价
	const total = await db.total('order', {})
	const date = new Date()
	const nowDate = String(date.getFullYear()) + String(date.getMonth() + 1) + String(date.getDate() < 10 ?
		'0' + date.getDate() : date.getDate())
	const index = 'qtj-' + nowDate + '0000' + String(total + 1)
	const nowTime = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + (date.getDate() < 10 ? '0' +
			date.getDate() : date.getDate()) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date
		.getSeconds()
	const data = await db.insert('order', {
		index,
		tableNum,
		totalMoney,
		status: 0,
		peopleNum,
		dishInfo,
		notes,
		time: nowTime
	})
	ctx.body = { success: true, code: 20000, message: "数据新增成功", data }
})

// 修改
router.post('/modify', async ctx => {
	const { _id, tableNum, totalMoney, peopleNum, dishInfo, notes, status } = ctx.request.body
	const data = await db.update('order', { _id }, {
		tableNum,
		totalMoney,
		status,
		peopleNum,
		dishInfo,
		notes
	})
	ctx.body = { success: true, code: 20000, message: "数据修改成功", data }
})

// 删除
router.get('/delete', async ctx => {
	const { _id } = ctx.request.query
	const data = await db.delete('order', { _id })
	ctx.body = { success: true, code: 20000, message: "数据删除成功", data }
})


module.exports = router
